package com.zjw.zy.coreui.fragment.tips

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zjw.zy.R
import com.zjw.zy.base.BaseFragment
import com.zjw.zy.base.BaseRecyclerAdapter
import com.zjw.zy.bean.Tip
import com.zjw.zy.coreui.fragment.adapter.TipListAdapter
import com.zjw.zy.coreui.fragment.holder.TipHolder
import com.zjw.zy.ext.goWithTopAnim
import com.zjw.zy.utils.PhoneUtils
import com.zjw.zy.utils.taskpool.TaskPool
import com.zjw.zy.viewmodel.TipsViewModel

/**
 * @author     ：zhong.jw
 * @date       ：Created in 2022/11/2 14:02
 * @description：
 */
class TipsListFragment : BaseFragment() {

    companion object {
        private const val TAG = "TipsListFragment"
    }

    private val tipViewModel: TipsViewModel by viewModels(ownerProducer = {
        requireParentFragment()
    })

    private val mList: RecyclerView by lazy { findViewById(R.id.fragment_tips_list) }

    private val mAdapter: TipListAdapter by lazy {
        TipListAdapter(object : BaseRecyclerAdapter.ItemListener<TipHolder> {
            override fun onCallbackOtherEvent(event: String, vararg args: Any?) {
                when (event) {
                    TipHolder.FINISH_EVENT -> {
                        //finish
                        val tip = args[0] as Tip
                        //增加一个震动效果
                        PhoneUtils.vibrator(500L, 50)
                        tipViewModel.finishTip(tip) {
                            TaskPool.backGround().postDelayed({
                                tipViewModel.refreshLastRequest()
                            }, 1000L)
                        }
                    }

                    TipHolder.DETAIL_EVENT -> {
                        goWithTopAnim(R.id.nav_tips_edit_fragment, Bundle().apply {
                            putParcelable(TipEditFragment.DATA_KEY, args[0] as Tip)
                        })
                    }
                }

                super.onCallbackOtherEvent(event, *args)
            }
        })
    }

    override fun onPageEnter() {

    }

    override fun onViewRestore(savedInstanceState: Bundle?) {

    }

    override fun onSubscribe() {
        tipViewModel.getTips().observe(this) {
            mAdapter.notifyDataWithDiff(it)
        }
    }

    override fun onBindViewListener() {

    }

    override fun onBindViewValue() {

        mList.adapter = mAdapter
        mList.layoutManager = LinearLayoutManager(context)
    }

    override fun onFindView(rootView: View?) {

    }

    override fun onLayoutId(): Int {
        return R.layout.fragment_tips_list
    }

    override fun onPageExit() {

    }
}